<template>
  <div>
    <van-field
      readonly
      clickable
      :value="vModelValue"
      :name="name"
      :label="label"
      :required="required"
      :rules="required ? rules : []"
      :placeholder="placeholder ? placeholder : '请选择' + label"
      right-icon="arrow-down"
      @click="showPicker = true"
    />
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        :value-key="valueKey"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
import formMixin from './mixin'

export default {
  name: 'FormPicker',
  mixins: [formMixin],
  props: {
    value: {
      type: String,
      required: true
    },
    placeholder: {
      type: String,
      default: ''
    },
    columns: {
      type: Array,
      required: true
    },
    valueKey: {
      type: String,
      default: 'dictLabel'
    },
    findName: {
      type: String,
      default: 'dictValue'
    }
  },
  data() {
    return {
      showPicker: false
    }
  },
  computed: {
    vModelValue: {
      get() {
        const fintItem = this.columns.find(item => item[this.findName] === this.value)
        return fintItem !== undefined ? fintItem[this.valueKey] : ''
      },
      set(val) {
        this.$emit('change', val[this.findName])
      }
    }
  },
  methods: {
    onConfirm(val) {
      this.$emit('change', val[this.findName])
      this.showPicker = false
    }
  }
}
</script>

<style lang="scss" scoped>
.van-radio {
  margin-top: 10px;
}

/deep/ {
  .van-radio__label {
    transition: color 0.5s;
  }
  .van-radio__icon--checked {
    & + .van-radio__label {
      color: #1989fa;
    }
  }
}
</style>
